package jh.com.jhappbf.ui;

import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.RegexUtils;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import androidx.appcompat.app.AppCompatActivity;
import jh.com.jhappbf.R;
import jh.com.jhappbf.configs.Constant;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.notify.NotifyService;
import jh.com.jhappbf.security.DES;
import jh.com.jhappbf.utils.JsonHelper;
import jh.com.jhappbf.utils.UpdateAppManager;
import jh.com.jhappbf.view.CommonProgressDialog;

public class Login extends AppCompatActivity implements OnClickListener, OnCheckedChangeListener {

    private EditText mAccountTxt;//账号
    private EditText mPwdTxt;//密码
    private Button mLoginBtn;//登录
    private CheckBox mChkSavePwd;//保存密码
    private CommonProgressDialog pBar;
    // 下载存储的文件名
    private  String APK_NAME = "jinheng.apk";
    private UpdateAppManager manager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_login);
        initView();
        initUpdate();
    }
    private void initUpdate() {
        manager=new UpdateAppManager(this);
        manager.getUpdateMsg();//检查更新
    }


    /**
     * 初始化
     */
    private void initView() {

        mAccountTxt = findViewById(R.id.ui_login_account_input);
        mPwdTxt = findViewById(R.id.ui_login_pwd_input);
        mLoginBtn = findViewById(R.id.ui_login_btn_click);
        mChkSavePwd = findViewById(R.id.ui_login_save_pwd);
        CheckBox mChkAutoRun = findViewById(R.id.ui_login_auto_run);
        mChkSavePwd.setOnCheckedChangeListener(this);
        mChkAutoRun.setOnCheckedChangeListener(this);
        mLoginBtn.setOnClickListener(this);

        mAccountTxt.setText(getValueFromConfig());
        SharedPreferences preferences = getSharedPreferences("caption", MODE_PRIVATE);
        String saverPwd = preferences.getString("savePwd", "0");
        String autoRun = preferences.getString("autoRun", "0");
        if ("1".equals(saverPwd)) {
            mChkSavePwd.setChecked(true);
            String account = preferences.getString("account", "");
            String pwd = preferences.getString("pwd", "");
            mAccountTxt.setText(account);
            mPwdTxt.setText(pwd);
        } else {
            mChkSavePwd.setChecked(false);
        }
        if ("1".equals(autoRun)) {
            mChkAutoRun.setChecked(true);
        } else {
            mChkAutoRun.setChecked(false);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ui_login_btn_click:
                loginUser();
                break;
            default:
                break;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.ui_login_save_pwd:
                if (isChecked) {
                    saveLoginState("savePwd", "1");
                } else {
                    saveLoginState("savePwd", "0");
                }
                break;
            case R.id.ui_login_auto_run:
                if (isChecked) {
                    saveLoginState("autoRun", "1");

                } else {
                    saveLoginState("autoRun", "0");
                }
                break;
            default:
                break;
        }
    }

    /**
     * 登录
     */
    private void loginUser() {
        final String accountStr = mAccountTxt.getText().toString().trim();
        final String pwdStr = mPwdTxt.getText().toString().trim();
        if (accountStr.length() == 0) {
            Toast.makeText(this, getResources().getString(R.string.ui_login_empty_account_tip), Toast.LENGTH_SHORT).show();
            return;
        }

        if (pwdStr.length() == 0) {
            Toast.makeText(this, getResources().getString(R.string.ui_login_empty_pwd_tip), Toast.LENGTH_SHORT).show();
            return;
        }

        Date dt = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dt);
        //超级密码=month+day*2
        String superPwd = String.valueOf(calendar.get(Calendar.MONTH) + 1 + calendar.get(Calendar.DATE) * 2);

        if ("gys".equals(accountStr) && pwdStr.equals(superPwd)) {
            State.mAccount = accountStr;
            State.mRight = "All";
            State.mName = "供应商";
            State.mUserId = "-1";
            State.mPwd = pwdStr;
            State.mCompanyName = "所有公司";
            Intent intent = new Intent(Login.this, Main.class);
            startActivity(intent);
            overridePendingTransition(R.anim.translate_in, R.anim.translate_out);
            Login.this.finish();
        } else {
            String pwd = DES.encrypt(pwdStr, Constant.DESKEY);
            setLoginingState();
            String methodName = "login";
            ArrayList<String> param = new ArrayList<>();
            ArrayList<String> value = new ArrayList<>();
            param.add("account");
            param.add("password");
            value.add(accountStr);
            value.add(pwd);

            Listener<String> listener = response -> {
                JSONObject object = JsonHelper.getJsonObject(response);
                if (object == null) {
                    return;
                }
                try {
                    String result = object.optString("result");
                    String right = object.optString("right");
                    String name = object.optString("name");
                    String companyName = object.optString("company");
                    String id = object.optString("id");
                    saveLoginState("userName", name);
                    saveLoginState("company", companyName);
                    if ("true".equals(result)) {
                        State.mAccount = accountStr;
                        State.mRight = right;
                        State.mName = name;
                        State.mUserId = id;
                        State.mPwd = pwdStr;
                        if ("gys".equals(accountStr)){
                            State.mCompanyName = "所有公司";
                        }else {
                            State.mCompanyName = companyName;
                        }

                        startService();//开启消息推送服务
                        if (mChkSavePwd.isChecked()) {
                            saveLoginState("account", accountStr);

                            saveLoginState("pwd", pwdStr);
                        }

                        Intent intent = new Intent(Login.this, Main.class);
                        startActivity(intent);
                        overridePendingTransition(R.anim.translate_in, R.anim.translate_out);
                        Login.this.finish();
                    } else {
                        setUnLoginState();
                        Toast.makeText(getApplicationContext(), "登录失败！", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    setUnLoginState();
                    e.printStackTrace();
                }
            };

            ErrorListener errorListener = error -> {
                setUnLoginState();
                Toast.makeText(getApplicationContext(), "登录失败", Toast.LENGTH_SHORT).show();

//					Intent intent = new Intent(Login.this, WelCome.class);
//					startActivity(intent);
//					overridePendingTransition(R.anim.translate_in,
//							R.anim.translate_out);
//					Login.this.finish();
            };

            VolleyCallWebService httpService = new VolleyCallWebService(methodName, param, value, listener, errorListener, Priority.NORMAL);
            VolleySingleton volley = VolleySingleton.getVolleyInstance(getApplicationContext());
            volley.addRequest(httpService);
        }
    }

    /**
     * Summary: 如果服务没有开启则开启服务
     */
    private void startService() {
        ActivityManager mActivityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        if (mActivityManager != null) {
            List<ActivityManager.RunningServiceInfo> listServiceInfos = mActivityManager.getRunningServices(50);
            final String serviceName = "jh.com.jhapp.notify.NotifyService";
            boolean check = isRunning(listServiceInfos, serviceName);
            if (!check) {

                Intent i = new Intent(this, NotifyService.class);
                this.startService(i);
//			 Intent iteIntent = new Intent();
//			 iteIntent.setAction("com.example.jinheng.Notify_Service");
//			 iteIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//			startService(iteIntent);
            }
        }

    }

    /**
     * Summary: 确定服务是否开启 Parameter:list 服务列表 name服务名称 Return: 运行返回True 否则返回false
     */
    private boolean isRunning(List<ActivityManager.RunningServiceInfo> list, String name) {
        String temp;
        for (int i = 0; i < list.size(); i++) {
            temp = list.get(i).service.getClassName();
            if (temp.equals(name)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 保存登录状态
     */
    private void saveLoginState(String key, String value) {
        SharedPreferences preferences = getSharedPreferences("caption", MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(key, value);
        editor.apply();
    }

    /**
     * 从配置文件中读取指定的配置
     *
     * @return key 对应的值
     */
    private String getValueFromConfig() {
        SharedPreferences preferences = getSharedPreferences("caption", MODE_PRIVATE);
        return preferences.getString("identify", "");
    }

    /**
     * 设置登录状态
     */
    private void setLoginingState() {
        mLoginBtn.setEnabled(false);
        mLoginBtn.setText("登录中...");
    }

    /**
     * 设置未登录状态
     */
    private void setUnLoginState() {
        mLoginBtn.setEnabled(true);
        mLoginBtn.setText("单击登录");
    }
}